package cn.edu.sdyu.ie.crs.common.util;

import cn.edu.sdyu.ie.crs.domain.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author: JT
 * @date: 2021/9/6
 * @Title:
 */
public class SpringSecurityUtil {

    /**
     * 获取当前登录的所有认证信息
     * @return
     */
    public static Authentication getAuthentication(){
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    public static User getUserInfo(){
        Authentication authentication = getAuthentication();
        if(authentication!=null){
            Object principal = authentication.getPrincipal();
            if(principal!=null){
                User user = (User) authentication.getPrincipal();
                return user;
            }
        }
        throw new RuntimeException("获取当前登录信息失败");
    }

    /**
     * 获取当前登录用户ID
     * @return
     */
    public static String getUserId(){
        User user = getUserInfo();
        return String.valueOf(user.getId());
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    public static void main(String[] args) {
        String text = "admin";
        System.out.println(SpringSecurityUtil.encryptPassword(text));
    }
}
